package java.web.java_web_ch08;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

public class DatabaseConnection {
    private static final Properties properties = new Properties();
    static {
        try (InputStream input = DatabaseConnection.class.getClassLoader().getResourceAsStream("db.properties")) {
            // 加载properties文件
            properties.load(input);
            // 加载JDBC驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (IOException | ClassNotFoundException e) {
            System.out.println("MySQL JDBC 驱动未找到 或者 属性文件加载失败.");
            e.printStackTrace();
        }
    }
    public static Connection getConnection() {
        try {
            final String url      = properties.getProperty("URL");
            final String user     = properties.getProperty("USER");
            final String password = properties.getProperty("PASSWORD");
            return DriverManager.getConnection(url, user, password);
        } catch (SQLException e) {
            System.out.println("数据库连接失败.");
            e.printStackTrace();
        }
        return null;
    }
    public static void main(String[] args) {
        try (Connection conn = DatabaseConnection.getConnection()) {
            if(conn != null){
                System.out.println("成功连接到 BookStore 数据库。");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}